<?php

namespace app\wxapp\controller;
use think\Request;
use think\Db;
use app\wxapp\model\Agency;
use app\wxapp\model\Cars;
use app\common\request\ClientLai;
use app\common\model\Terminal;
use think\Log;
use app\common\request\Command;

class Api {
	private $token = 'f30173557ee54d6e9c60857ee30889a2';

	private $agency = [
		2=>50,
		3=>45,
		4=>44,
		5=>34,
		7=>49,
		8=>35,
		23=>63,
		24=>73,
		28=>64,
		29=>66,
		30=>65,
		32=>46,
		34=>68,
		35=>69,
		37=>67
	];

	public function cars(){
		$request = Request::instance();
		$data = $request->param();
		if($data['token'] != $this->token){
			return [
                'code'=>1,
                'msg'=>'身份不合法'
            ];
		}

		if(!empty($data['car_sn'])){

			if(is_array($data['car_sn'])){
				$data['car_sn'] = array_filter($data['car_sn']);
			}

			try{

				$res = Db::name('cars')->where('car_sn','in',$data['car_sn'])->where(['delete_time'=>null])->limit(10)->field('car_unique_id,car_sn,cardcode')->select();

			}catch(\Exception $e){
				return [
	                'code'=>1,
	                'msg'=>$e->getMessage()
	            ]; 
			}

			if($res){
				return [
					'code'=>0,
					'msg'=>'成功',
					'data'=>$res
				];
			}else{
				return [
	                'code'=>1,
	                'msg'=>'车牌号不存在'
	            ];
			}
			
		}else{
			return [
	            'code'=>2,
	            'msg'=>'车牌号不能为空'
	        ];
		}

		
	}

	public function card(){
		$request = Request::instance();
		$data = $request->param();
		if($data['token'] != $this->token){
			return [
                'code'=>1,
                'msg'=>'身份不合法'
            ];
		}
		try{

			$res = Db::name('cars')->where('sim_id','in',$data['sim_id'])->where(['delete_time'=>null])->limit(10)->field('cardcode,sim_id,equipment_id')->select();

		}catch(\Exception $e){
			return [
                'code'=>1,
                'msg'=>$e->getMessage()
            ];
		}

		if($res){
			return [
				'code'=>0,
				'msg'=>'成功',
				'data'=>$res
			];
		}else{
			return [
                'code'=>1,
                'msg'=>'卡序列号不存在'
            ];
		}
	}

	public function total_cars($agency_id='',$token=""){
		if($token != $this->token){
			return [
                'code'=>1,
                'msg'=>'身份不合法'
            ];
		}
		$agency_array = explode(',', $agency_id);

        $array = [];
        
        $model = Agency::withCount(['cars'=>function($query){
                                        $query->where('car_usage',3);
                                    }])->select();
        
        $carsTotal = Cars::count();
        

        foreach ($model as $key => $value) {
            $array[$key]['total'] = $value->cars_count;
            $array[$key]['franchisee_id'] = $value->id;
            $array[$key]['car_total'] = Cars::where(['agency_id'=>$value->id])->count();
        }
 
        $franchisee = ['car_total'=>$carsTotal,'franchisee_map'=>[]];
        if(empty($agency_id)){
        	$franchisee['rent_total'] = Cars::where('car_usage',3)->count();
        	foreach ($array as $key => $value) {
        		if(!empty($this->agency[$value['franchisee_id']])){
        			array_push($franchisee['franchisee_map'], ['car_total'=>$value['car_total'],'total'=>$value['total'],'franchisee_id'=>$this->agency[$value['franchisee_id']]]);
        			
        		}
        	}

		}else{
			$franchisee_array = [];
			$rent_total = 0;
			foreach ($this->agency as $key => $value) {
				if(in_array($value, $agency_array)){
					$franchisee_array[$key]=$value;
					$rent_total += Cars::where(['car_usage'=>3,'agency_id'=>$key])->count();
				}
			}     	
			$franchisee['rent_total'] = $rent_total;
			foreach ($array as $key => $value) {
        		if(!empty($franchisee_array[$value['franchisee_id']])){
        			array_push($franchisee['franchisee_map'], ['car_total'=>$value['car_total'],'total'=>$value['total'],'franchisee_id'=>$franchisee_array[$value['franchisee_id']]]);
        			
        		}
        	}

		}
       	return ['code'=>0,'msg'=>'成功','data'=>$franchisee];
	}


	public function register($simId="",$deviceName="",$token=""){
		if($token != $this->token){
			return ['code'=>1,'msg'=>'身份不合法'];
		}

		if($simId == "" || $deviceName == ""){
			return ['code'=>1,'msg'=>'参数不能为空'];
		}else{

			$arr = $this->registerDevice($deviceName);

			if(!empty($arr)){
				$model = new Terminal();
        		$terminal = $model::where(['equipment_id'=>$deviceName,'sim_id'=>$simId])->find();
        		if($terminal){
        			try{
                        $model->where(['equipment_id' => $deviceName])->update(['status' => 1]);
                    }catch(\Exception $e){
                    	Log::record('[ terminal状态更新失败 ]'.$e->getMessage(),'error');
                    }

					return [
						'code'=>0,
						'msg'=>'成功',
						'data'=>[
							'productKey'=>$arr['productKey'],
							'deviceSecret'=>$arr['deviceSecret'],
							'deviceName'=>$arr['deviceName'],
							'cardCode'=>$terminal['cardcode'],
							'simId'=>$terminal['sim_id']
						]
					];
        		}else{
        			$cardcode = $this->queryCardCode($simId);
					if(!empty($cardcode)){
						$res = $this->saveData($cardcode,$simId,$deviceName);
						if($res){
							return [
								'code'=>0,
								'msg'=>'成功',
								'data'=>[
									'productKey'=>$arr['productKey'],
        							'deviceSecret'=>$arr['deviceSecret'],
        							'deviceName'=>$arr['deviceName'],
        							'cardCode'=>$cardcode,
        							'simId'=>$simId
								]
							];
						}
					}else{
						return ['code'=>2,'msg'=>'卡号为空','data'=>[]];
					}
        		}
				
			}else{
				return ['code'=>3,'msg'=>'设备注册失败','data'=>[]];
			}
			
		}

	}


	public function registerDevice($deviceName=""){
		$data['device_name'] = $deviceName;

		$config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);
        $res = $obj->request_post(rtrim($config['url'],'/').'/device/registDevice',$data);

        $arr = json_decode($res,true);

        if(!empty($arr) && $arr['result'] == 0){
        	if($arr['data'][0]['success'] == true){
        		$details = $this->queryDeviceDetail($deviceName);
        	}else{
        		$details = $this->queryDeviceDetail($deviceName);
        	}
        	if(!empty($details)){
        		return $details;
        	}else{
        		return [];
        	}
        	
        }else{
        	Log::record('[ 设备注册失败 ]'.$arr['msg'],"error");
        	return [];
        }

	}


	public function queryDeviceDetail($deviceName){
		$data['device_name'] = $deviceName;
		$config = config('local_iot');
        $obj = new ClientLai($config['user_name'],$config['password']);

        $data['device_name'] = $deviceName;
        $res = $obj->request_post(rtrim($config['url'],'/').'/device/queryDeviceDetail',$data);
        if($res){
            $arr = json_decode($res,true);
        	if($arr['result'] == 0 && !empty($arr['data'])){
        		$dataum = $arr['data'][0]['data'];
        	}else{
        		Log::record('[ 查询设备信息失败 ]'.$arr['msg'],"error");
        		$dataum = [];
        	}
            
        }else{
            $dataum = [];
        }
        
        return $dataum;
	}

	public function queryCardCode($simId){
		$arr = $this->queryAliCardCode($simId);
		if(!empty($arr)){
			$cardcode = $arr['msisdn'];
		}else{
			$dataum = $this->querySaiKaCardCode($simId);
			if(!empty($dataum)){
				$cardcode = $dataum['cardcode'];
			}else{
				$cardcode = "";
			}		
		}

		return $cardcode;
		
	}

	public function queryAliCardCode($simId){
		$data['iccid'] = $simId;
        $url = "http://120.79.71.83:81/card_status";
        $content = Command::response($data,$url);
        if(!empty($content)){
            $arr = json_decode($content,true);
            if($arr['code'] == 0){
                if(!empty($arr['data'])){
                    return $arr['data']['cardStatus'];
                }else{
                	return "";
                }
            }else{
            	return "";
            }
        }
	}



	public function querySaiKaCardCode($simId){
		$config = config('sk_api'); 
        $data['partnercode'] = $config['partnercode'];
        $data['servicecode'] = $config['servicecode'];
        $data['requesttime'] = date('YmdHis').'2500000001';
        $data['key'] = $simId;
        $data['status'] = 2;
        $string = $config['password'].$data['requesttime'].$data['key'].$data['status'];
        $data['sign'] = md5(strtolower($string));
        $url = rtrim($config['url'],'/').'/M2MSearchTermInfo.ashx';
        $content = $this->demand($url,$data);
        if($content){
            $arr = json_decode($content,true);
            if($arr['status'] == 0000){
                return $arr['result'][0];
                
            }else{
                return "";
            }
        }
	}
	

	public function saveData($cardCode,$simId,$deviceName){
		$param['cardcode'] = $cardCode;
		$param['sim_id'] = $simId;
		$param['equipment_id'] = $deviceName;
		$param['supplier_no'] = 1376920002;
		$param['status'] = 1;

		$model = new Terminal();
		try{
			$model->save($param);

		}catch(\Exception $e){
			Log::record('[ 设备注册添加失败 ]'.$e->getMessage(),"error");
			return false;
		}

		return true;
	}


	public function demand($url,$json){
        $url = $url; 
        $data = json_encode($json);
        $curl = curl_init($url);  // 初始化 cURL 会话
        curl_setopt($curl, CURLOPT_HEADER, false);  // 启用时会将头文件的信息作为数据流输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));  //设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100') 
        curl_setopt($curl, CURLOPT_POST, true);     //TRUE 时会发送 POST 请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  // 全部数据使用HTTP协议中的 "POST" 操作来发送。value必须是个数组
        $content = curl_exec($curl);  // 执行 cURL 会话 , 应该在初始化一个 cURL 会话并且全部的选项都被设置后被调用。 
        if(curl_errno($curl)){
            $content = [];
            Log::record(curl_errno($curl),'error');          
        }else{

            $info = curl_getinfo($curl);   // 获取一个cURL连接资源句柄的信息(获取最后一次传输的相关信息)
        
            if($info['http_code'] !== 200){

                $content = [];
                Log::record('对方服务器错误','error');
                
            }
        }
        
        curl_close($curl); // 关闭 cURL 会话
        return $content;
        
    }


}
